<?php
namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Models\MAddress;
use App\Models\MExpressCompany;
use App\Models\MOrder;
use App\Models\MProduct;
use App\Models\MUser;
use App\Models\MUserAttr;
use App\Utils\ShoppingCar;
use DB;
use Illuminate\Http\Request;

/**
 * 在线购物商城控制器
 */
class ProductController extends Controller
{
    /**
     * 购物中心界面
     */
    public function productsPage(Request $request, $index = 1)
    {
        $this->fyInit(route('sys.products'), 16)->fyCalc(MProduct::where('status', MProduct::$STATUS_SALE)->count(), $index);
        $this->data['products'] = MProduct::where('status', MProduct::$STATUS_SALE)->skip($this->fy_pgOffset)->take($this->fy_pgSize)->get();
        $this->fyViewInit($this->data);
        return view("system.products")->with($this->data);
    }

    /**
     * 加入商品到购物车
     */
    public function addCart(Request $request)
    {
        if (!$request->has(['no', 'buy-num'])) {
            $this->data = $this->makeJsCode(1, "数据验证失败！");
            return response()->json($this->data);
        }

        if (!is_numeric($request->input('buy-num')) || $request->input('buy-num') <= 0) {
            $this->data = $this->makeJsCode(1, "加入失败，请选择大于0的商品数量！");
            return response()->json($this->data);
        }

        $car = new ShoppingCar();
        if ($car->add($request->no, $request->input("buy-num"))) {
            $this->data = $this->makeJsCode(0, "加入成功！");
        } else {
            $this->data = $this->makeJsCode(1, "加入失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 删除购物车里面的商品
     */
    public function delCart($no)
    {
        $car = new ShoppingCar();
        if ($car->del($no)) {
            $this->data = $this->makeJsCode(0, "删除成功！");
        } else {
            $this->data = $this->makeJsCode(1, "删除失败！");
        }
        return back()->with($this->data);
    }

    /**
     * 购物车页面
     */
    public function cartsPage()
    {
        $car = new ShoppingCar();
        $this->data['carts'] = MProduct::whereIn('no', $car->no())->get();
        $this->data['cart'] = $car->cart;
        $this->data['total'] = $car->calc();
        return view("system.carts")->with($this->data);
    }

    /**
     * 购物车结算操作
     */
    public function orderCreate(Request $request)
    {
        //检查二级密码
        $user = MUser::find(ss('uid'));
        if (!$request->has('safepass') || $request->safepass != $user->safepass) {
            $this->data = $this->makeJsCode(1, "支付密码错误！");
            return response()->json($this->data);
        }

        //判断是否有收货地址
        $addr = MAddress::where('uid', ss('uid'))->first();
        if (empty($addr)) {
            $this->data = $this->makeJsCode(1, "请先完善您的收货地址再进行结算！");
            return response()->json($this->data);
        }

        $car = new ShoppingCar();
        $money = $car->calc();
        if ($money == 0) {
            $this->data = $this->makeJsCode(1, "购物车为空，不能结算！");
            return response()->json($this->data);
        }

        //判断购物币是否足够
        $wallet = $user->wallet;
        if ($wallet->w3 < $money) {
            $this->data = $this->makeJsCode(1, "您的账户余额不足！");
            return response()->json($this->data);
        }
        $wallet->w3 -= $money;

        DB::transaction(function () use (&$user, &$wallet, &$car, &$addr) {

            if ($wallet->save() && MOrder::createOrder($user, $car, $addr)) {
                $this->data = $this->makeJsCode(0, "支付成功！");
            } else {
                DB::rollBack();
                $this->data = $this->makeJsCode(1, "支付失败！");
            }

        });

        return response()->json($this->data);
    }

    /**
     * 我的订单列表页面
     */
    public function ordersPage($index = 1)
    {
        $this->fyInit(route('sys.orders'), 15)->
        fyCalc(MOrder::where('uid', ss('uid'))->count(), $index);

        $this->data['orders'] = MOrder::where('uid', ss('uid'))->get();
        $this->fyViewInit($this->data);
        return view("system.shopping_logs")->with($this->data);
    }

    /**
     * CURL获取物流信息
     * @param $oid  订单ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function expressInfo($oid)
    {
        $order = MOrder::find($oid);
        $short_name = MExpressCompany::find($order->express_company_id)->alias; //快递公司简称
        $no = $order->express_no;

        $curl = curl_init();
        //设置选项，包括URL
        curl_setopt($curl, CURLOPT_URL, "http://www.kuaidi100.com/query?type=" . $short_name . "&postid=" . $no);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $data = curl_exec($curl);
        //释放curl句柄
        curl_close($curl);

        return response()->json($data);
    }

    /**
     * 我的收货地址页面
     */
    public function addressPage()
    {
        $this->data['addr'] = MAddress::where('uid', ss('uid'))->first();
//        dd($this->data['addr']);
        return view("system.address")->with($this->data);
    }

    /**
     * 收货地址存储请求
     */
    public function addrSave(Request $request)
    {
        if (count($request->rule) > 0) {//验证自动添加的属性规则
            for ($i = 0; $i < count($request->rule); $i++) {
                $rule = unserialize($request->rule[$i]);
                $msg = unserialize($request->msg[$i]);
                if (!$this->validateReq($request, $rule, $msg)) {
                    $this->data = $this->makeJsCode(1, $this->errors->first());
                    return response()->json($this->data);
                }
            }
        }
        if (!$this->validateReq($request, MAddress::saveRulesWithMsg(0),
            MAddress::saveRulesWithMsg(1))
        ) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        if (MAddress::saveAddress($request, ss('uid')) && MUserAttr::userInfo(ss('uid'), $request->all())) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }
        return response()->json($this->data);
    }
}